package com.qf.java2201.web;

import com.qf.java2201.pojo.HUser;
import com.qf.java2201.service.UserService;
import com.qf.java2201.service.impl.UserServiceImpl;
import com.qf.java2201.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @date 2022/4/6
 * @desc   登录功能
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uname = req.getParameter("uname");

        // 接的是明文密码
        String upwd = req.getParameter("upwd");
        String remember = req.getParameter("remember");

        //把参数封装到对象中
        HUser hUser = new HUser();

        // 因为 要和  数据库中的 加密密码 比对  所以对明文密码进行加密
        String md5upwd = MD5Util.encodePwdByMD5(upwd);
        hUser.setUpwd(md5upwd);

        hUser.setUname(uname);

        UserService userService = new UserServiceImpl();


        HUser result = userService.login(hUser);

        HttpSession session = req.getSession();

        if(result!=null){
            //登陆成功  再判断用户是否勾选了 记住我
            if(remember!=null){
                // 发送cookie
                Cookie cookie = new Cookie("remember",result.getUname()+"-"+upwd);

                cookie.setMaxAge(Integer.parseInt(remember));

                resp.addCookie(cookie);
            }
            // 登录成功  跳转到 index.jsp
            session.setAttribute("u",result);
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }else{
            // 登陆失败   跳转到 login.jsp
            req.setAttribute("log_info","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }




    }
}
